import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/auth/Login.vue'),
      meta: { title: '登录' }
    },
    {
      path: '/register',
      name: 'Register',
      component: () => import('@/views/auth/Register.vue'),
      meta: { title: '注册' }
    },
    {
      path: '/',
      component: () => import('@/layouts/BasicLayout.vue'),
      children: [
        {
          path: '',
          name: 'Home',
          component: () => import('@/views/home/Index.vue'),
          meta: { title: '首页' }
        },
        {
          path: 'restaurant/list',
          name: 'RestaurantList',
          component: () => import('@/views/restaurant/List.vue'),
          meta: { title: '餐厅列表' }
        },
        {
          path: 'restaurant/:id',
          name: 'RestaurantDetail',
          component: () => import('@/views/restaurant/Detail.vue'),
          meta: { title: '餐厅详情' }
        },
        {
          path: 'search',
          name: 'Search',
          component: () => import('@/views/search/Index.vue'),
          meta: { title: '搜索结果' }
        },
        {
          path: 'user/profile',
          name: 'User',
          component: () => import('@/views/user/Profile.vue'),
          meta: {
            title: '个人中心',
            requiresAuth: true
          }
        },
        {
          path: '/user/orders',
          name: 'OrderList',
          component: () => import('@/views/order/List.vue'),
          meta: {
            title: '我的订单',
            requiresAuth: true
          }
        }
      ]
    }
  ]
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 餐饮预订系统` : '餐饮预订系统'

  const token = localStorage.getItem('user_token')
  const expireTime = localStorage.getItem('expireTime')

  // 检查token是否过期
  const checkTokenExpired = () => {
    if (!expireTime) return true
    return new Date().getTime() > parseInt(expireTime)
  }

  if (to.path === '/login' || to.path === '/register') {
    if (token && !checkTokenExpired()) {
      next('/')
    } else {
      next()
    }
  } else {
    if (!token || checkTokenExpired()) {
      if (token) {
        ElMessage.warning('登录已过期，请重新登录')
        localStorage.removeItem('user_token')
        localStorage.removeItem('userInfo')
        localStorage.removeItem('expireTime')
      }
      next('/login')
    } else {
      next()
    }
  }
})

export default router
